<script setup lang="ts">
import {
  Deployment,
  StatefulSet,
  DaemonSet,
  NodeInfo,
  Namespace,
  Service,
  Secret,
  ConfigMap,
  ClusterInfo,
  Volume,
  useK8SApi,
  VolumeMount,
  PodSpec
} from "@/views/domain/kubeHud/api/k8s";
import { useFormRule } from "@/views/domain/kubeHud/utils/rules";
import KSection from "@/views/domain/kubeHud/views/components/k-section/index.vue";
import KSegment from "@/views/domain/kubeHud/views/components/k-segment/index.vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import koVolumeMount from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-volume-mount.vue";

import { useI18n } from "vue-i18n";
import { WorkloadType } from "../provider";
import { computed, onMounted, reactive, ref } from "vue";
import PVCSelector from "../../storage/pvc/widgets/PVCSelector.vue";
import PodVolumeMountItem from "./PodVolumeMountItem.vue";

const { pvcRepo } = useK8SApi();

type WorkloadEntity = Deployment | StatefulSet | DaemonSet | any;

type Prop = {
  type?: WorkloadType;
  readonly?: boolean;
  nodeList?: NodeInfo[];
  namespaceList?: Namespace[];
  serviceList?: Service[];
  secretList?: Secret[];
  configMapList?: ConfigMap[];
  clusterList?: ClusterInfo[];
};

const { t } = useI18n();
const { NumberRule } = useFormRule();

const props = defineProps<Prop>();
const workload = defineModel<WorkloadEntity>();
const spec = computed<PodSpec>(() => workload.value.spec.template.spec);

type UIContainerVolume = {
  volume?: Volume;
  containerMounts?: { container: string; mounts?: VolumeMount }[];
};

const containerVolumes = ref<UIContainerVolume[]>([]);

const findMount = (name: string): VolumeMount | undefined => {
  for (const c of spec.value.containers ?? []) {
    const idx = c.volumeMounts?.findIndex(v => v.name === name);
    if (idx < 0) {
      continue;
    }

    return c.volumeMounts[idx];
  }
};

const findVolume = (name: string): Volume | undefined => {
  const idx = spec.value.volumes?.findIndex(v => v.name === name);
  if (idx < 0) {
    return;
  }

  return spec.value.volumes[idx];
};

const reloadUIVolumeMounts = () => {
  containerVolumes.value =
    spec.value.volumes?.map(v => {
      return {
        volume: v,
        containerMounts: spec.value.containers?.map(c => {
          return {
            container: c.name,
            mounts: findMount(v.name)
          };
        })
      };
    }) ?? [];
};

const addPVC = () => {
  const volume: Volume = { name: "", persistentVolumeClaim: {} };
  spec.value.volumes?.push(volume);

  containerVolumes.value.push({
    volume,
    containerMounts: spec.value.containers?.map(c => {
      return {
        container: c.name
      };
    })
  });
};

const editVolume = reactive({
  type: "PersistentVolumeClaim"
});

const uiState = reactive({
  edit: false,
  volumeTypeList: [
    { label: "持久卷", value: "PersistentVolumeClaim" },
    { label: "临时卷", value: "EmptyDir" },
    { label: "HostPath", value: "HostPath" },
    { label: "配置字典", value: "ConfigMap" },
    { label: "保密字典", value: "Secret" }
  ]
});

const onAddVolume = () => {
  editVolume.type = "PersistentVolumeClaim";
  uiState.edit = true;
  spec.value.volumes = [...(spec.value.volumes ?? []), {}];
};

onMounted(() => {
  if (!spec.value.volumes) {
    spec.value.volumes = [];
  }

  reloadUIVolumeMounts();
});
</script>

<template>
  <k-section title="存储设置">
    <el-collapse-transition>
      <div>
        <PodVolumeMountItem
          v-for="(volume, idx) in spec.volumes"
          :key="idx"
          v-model:containers="spec.containers"
          v-model:volume="spec.volumes[idx]"
          :namespace="workload.metadata.namespace"
        />
      </div>
    </el-collapse-transition>

    <div class="flex flex-row gap-4 flex-wrap mt-3">
      <div class="volume-add-row-item" @click="onAddVolume">
        <span>添加挂载卷</span>
      </div>
    </div>
  </k-section>
</template>
<style lang="scss" scoped>
.volume-add-row-item {
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  padding: 10px;
  border: 1px dashed var(--el-border-color);
  transition: all 0.3s;
  min-height: 60px;

  > span {
    font-size: 16px;
  }

  > div {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  &:hover {
    border: 1px dashed var(--el-color-primary);
    box-shadow: 0 0 2px var(--el-color-primary);
    cursor: pointer;
  }
}

.container-wrapper {
  padding: 10px;
  border: var(--el-border);
  display: flex;
  flex-wrap: wrap;

  .title {
    font-size: 14px;
    font-weight: bold;
    color: var(--el-text-color-primary);
  }
}

.edit-form-row {
  display: flex;
  width: 100%;
  flex-direction: column;
  gap: 10px;
}
</style>
